import {
  Form,
  Button,
  Col,
  Row,
  Input,
  DatePicker,
  Table,
  Popconfirm,
  InputNumber,
  Drawer,
} from "antd";
import React, { Component } from "react";
import moment from "moment";
import { Quotationdetail } from "../../../services/auth";
import { getToken } from "../../../utils/auth";
import { EditOutlined } from "@ant-design/icons";
import AddGoods from "./GoodsRow";

// form中的属性
const { RangePicker } = DatePicker;

export default class NEditQuotation extends Component {
  constructor(props) {
    super(props);
    const { quotation, handleEditClick } = this.props;
    this.quotation = quotation;
    this.handleEditClick = handleEditClick;
    // 父类的state
    this.state = {
      // 这个是商品数据
      dataSource: [],
      // 这个用于控制抽屉
      visible: false,
      count: 0,
      discountRate: this.quotation.discount / 100,
    };
    this.columns = [
      {
        title: "产品编号",
        dataIndex: "goods_id",
      },
      {
        title: "产品名称",
        dataIndex: "goods_name",
      },
      {
        title: "订货数量",
        dataIndex: "quantity",
      },
      {
        title: "产品定价",
        dataIndex: "price",
      },
      {
        title: "折扣",
        dataIndex: "discount",
        width: "10%",
        editable: true,
      },
      {
        title: "产品价格",
        dataIndex: "current_price",
        editable: true,
      },
      {
        title: "operation",
        dataIndex: "operation",
        render: (_, record) =>
          this.state.dataSource.length >= 1 ? (
            <Popconfirm
              title="Sure to delete?"
              onConfirm={() => this.handleDelete(record.key)}
            >
              <a>Delete</a>
            </Popconfirm>
          ) : null,
      },
    ];
    this.user = JSON.parse(getToken());
  }
  formRef = React.createRef();
  componentDidMount() {
    // 拿到原有的货物数据
    Quotationdetail(this.quotation.id).then(
      (response) => {
        // 通过addclick加入到state中
        for (let i = 0; i < response.data.goods.length; i++) {
          this.handleAddClick(response.data.goods[i]);
        }
      },
      (error) => {
        console.log("失败了", error);
      }
    );
  }
  // 传给抽屉用于新建商品的函数
  handleAddClick = (value) => {
    const { count, dataSource } = this.state;
    const newData = {
      key: count,
      ...value,
    };
    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1,
    });
  };
  // 用于编辑table的函数
  handleDelete = (key) => {
    const dataSource = [...this.state.dataSource];
    this.setState({
      dataSource: dataSource.filter((item) => item.key !== key),
    });
  };

  // 点击提交后触发的事件
  onFinish = (values) => {
    this.handleEditClick({
      id: this.quotation.id,
      goods: this.state.dataSource,
      ...values,
      operator_id: this.user.id,
      req_deliv_date: values.req_deliv_date.format("YYYY-MM-DD"),
      ship_to_address: values.ship_to_address,
      valid_from: values.valid[0].format("YYYY-MM-DD"),
      valid_to: values.valid[1].format("YYYY-MM-DD"),
    });
    this.onClose();
  };
  // 用于抽屉的函数
  showDrawer = () => {
    this.setState({
      visible: true,
    });
  };
  onClose = () => {
    this.setState({
      visible: false,
    });
  };
  onReset = () => {
    this.formRef.current.resetFields();
  };
  componentDidUpdate() {
    const { dataSource } = this.state;
    let sum = 0;
    for (let j = 0; j < dataSource.length; j++) {
      sum += dataSource[j].current_price * parseInt(dataSource[j].quantity);
    }
    sum = sum * this.state.discountRate;
    sum = sum.toFixed(2);
    if (this.formRef.current) {
      this.formRef.current.setFieldsValue({ total_price: sum });
    }
  }

  discountChange(value) {
    this.setState({
      discountRate: value / 100,
    });
  }

  render() {
    const { dataSource } = this.state;
    console.log(this.quotation);
    return (
      <div>
        <Button
          type="link"
          onClick={this.showDrawer}
          size="small"
          icon={<EditOutlined />}
          style={{ fontWeight: "bold" }}
          disabled={
            this.quotation.status !== "待回复" &&
            this.quotation.status !== "待发送"
          }
        >
          编辑
        </Button>
        <Drawer
          title="修改报价单信息"
          width={1000}
          onClose={this.onClose}
          visible={this.state.visible}
          bodyStyle={{ paddingBottom: 80 }}
        >
          <Form
            layout="vertical"
            hideRequiredMark
            onFinish={this.onFinish}
            ref={this.formRef}
          >
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item
                  name="company"
                  label="公司"
                  initialValue={
                    this.quotation.company_id +
                    " " +
                    this.quotation.company_name
                  }
                >
                  <Input disabled />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="ship_to_address"
                  label="送货地点"
                  rules={[{ required: true, message: "请输入送货地点" }]}
                  initialValue={this.quotation.ship_to_address}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col span={7}>
                <Form.Item
                  name="valid"
                  label="生效期限"
                  initialValue={[
                    moment(this.quotation.valid_from, "YYYY-MM-DD"),
                    moment(this.quotation.valid_to, "YYYY-MM-DD"),
                  ]}
                  rules={[{ required: true, message: "请填写生效期限" }]}
                >
                  <RangePicker />
                </Form.Item>
              </Col>
              <Col span={5}>
                <Form.Item
                  name="req_deliv_date"
                  initialValue={moment(
                    this.quotation.req_deliv_date,
                    "YYYY-MM-DD"
                  )}
                  label="预计送达日期"
                  rules={[{ required: true }]}
                >
                  <DatePicker />
                </Form.Item>
              </Col>
              <Col span={4}>
                <Form.Item
                  name="discount"
                  label="总折扣"
                  rules={[{ required: true }]}
                  initialValue={this.quotation.discount}
                >
                  <InputNumber
                    min={0}
                    max={100}
                    formatter={(value) => `${value}%`}
                    parser={(value) => value.replace("%", "")}
                    onChange={(number) => this.discountChange(number)}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  name="total_price"
                  label="总价"
                  rules={[{ required: true }]}
                >
                  <Input disabled />
                </Form.Item>
              </Col>
            </Row>
            <AddGoods handleAddClick={this.handleAddClick} />
            <Table
              bordered
              dataSource={dataSource}
              columns={this.columns}
              pagination={{ pageSize: 4 }}
            />
            <Form.Item>
              <div
                style={{
                  textAlign: "right",
                }}
              >
                <Button onClick={this.onClose} style={{ marginRight: 8 }}>
                  取消
                </Button>
                <Button htmlType="reset" style={{ marginRight: 8 }}>
                  重置
                </Button>
                <Button type="primary" htmlType="submit">
                  提交
                </Button>
              </div>
            </Form.Item>
          </Form>
        </Drawer>
      </div>
    );
  }
}
